package com.pjc.rpc.pool;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对象池工厂类
 * @author 王畅 
 * @version 创建时间：2015-6-16  上午09:24:25
 */
public class ThriftPoolObjectFacory implements PooledObjectFactory<TSocket> {

	private static final Logger log = LoggerFactory
			.getLogger(ThriftPoolObjectFacory.class);

	private String serviceIP;
	private int servicePort;
	private int timeOut;

	public ThriftPoolObjectFacory() {
	}

	public void init(String serviceIP, int servicePort, int timeOut) {
		this.serviceIP = serviceIP;
		this.servicePort = servicePort;
		this.timeOut = timeOut;
	}

	@Override
	public void activateObject(PooledObject<TSocket> arg0) throws Exception {
	}

	@Override
	public void destroyObject(PooledObject<TSocket> arg0) throws Exception {
		try {
			TSocket socket = arg0.getObject();
			if (socket.isOpen()) {
				socket.close();
			}

		} catch (Exception e) {
			log.error("error destroyObject()",e);
			throw new RuntimeException(e);
		}

	}

	@Override
	public PooledObject<TSocket> makeObject() throws Exception {
		try {
			TTransport transport = new TSocket(this.serviceIP,
					this.servicePort, this.timeOut);
			transport.open();
			return new DefaultPooledObject<TSocket>((TSocket) transport);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void passivateObject(PooledObject<TSocket> arg0) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean validateObject(PooledObject<TSocket> arg0) {
		try {
			TSocket socket = arg0.getObject();
			return socket.isOpen();

		} catch (Exception e) {
			return false;
		}

	}

}
